/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.model.NotifyTemplate;
import com.yami.shop.bean.model.NotifyTemplateShop;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.NotifyTemplateService;
import com.yami.shop.service.NotifyTemplateShopService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;


/**
 *
 * @author lhd
 * @date 2020-07-01 16:13:08
 */
@RestController
@AllArgsConstructor
@RequestMapping("/multishop/notifyTemplate" )
public class NotifyTemplateController {

    private final NotifyTemplateService notifyTemplateService;
    private final NotifyTemplateShopService notifyTemplateShopService;


    /**
     * 通过id查询
     * @param templateId id
     * @return 单个数据
     */
    @GetMapping("/info/{templateId}" )
    public ResponseEntity<NotifyTemplate> getById(@PathVariable("templateId") Long templateId) {
        NotifyTemplate template = notifyTemplateService.getById(templateId);
        Long shopId = SecurityUtils.getShopUser().getShopId();
        NotifyTemplateShop notifyTemplateShop = notifyTemplateShopService.getOne(new LambdaQueryWrapper<NotifyTemplateShop>()
                .eq(NotifyTemplateShop::getShopId, shopId).eq(NotifyTemplateShop::getTemplateId,template.getTemplateId()).last("limit 1"));
        template.setTemplateTypeList(getTemplateList(template.getTemplateTypes()));
        for (Integer type : template.getTemplateTypeList()) {
            template.setSms(type == 1 ? true:template.getSms());
            template.setApp(type == 3 ? true:template.getApp());
            template.setSub(type == 2 ? true:template.getSub());
        }
        if(Objects.nonNull(notifyTemplateShop)){
            template.setShopTemplateTypeList(getTemplateList(notifyTemplateShop.getNotifyTypes()));
        }
        replaceContent(template);
        return ResponseEntity.ok(template);
    }

    private void replaceContent(NotifyTemplate template) {
        if (StrUtil.isEmpty(template.getMessage())) {
            return;
        }
        String message = template.getMessage();
        Map<String,String> contentMap = new HashMap<>(24);
        contentMap.put("orderNumber","<订单编号>");
        contentMap.put("nickName","<用户昵称>");
        contentMap.put("day","<天数>");
        contentMap.put("hour","<小时>");
        contentMap.put("dvyTime","<发货时间>");
        contentMap.put("shopName","<店铺名称>");
        contentMap.put("cancelTime","<取消时间>");
        contentMap.put("levelName","<等级名称>");
        for(String key : contentMap.keySet()){
            message = message.replace("${" + key + "}", contentMap.get(key));
        }
        template.setMessage(message);
    }


    /**
     * @return 数据
     */
    @GetMapping("/getList" )
    public ResponseEntity<List<NotifyTemplate>> getNotifyTemplatePage() {
        List<NotifyTemplate> templates = notifyTemplateService.list(new LambdaQueryWrapper<NotifyTemplate>()
                .ne(NotifyTemplate::getSendType, SendType.CUSTOMIZE.getValue())
                .eq(NotifyTemplate::getMsgType,2)
                .orderByDesc(NotifyTemplate::getStatus).orderByDesc(NotifyTemplate::getCreateTime));
        if(CollectionUtils.isEmpty(templates)){
            return ResponseEntity.ok().build();
        }
        for (NotifyTemplate  template: templates) {
            List<Integer> templateList = getTemplateList(template.getTemplateTypes());
            for (Integer type : templateList) {
                template.setSms(type == 1 ? true:template.getSms());
                template.setSub(type == 2 ? true:template.getSub());
                template.setApp(type == 3 ? true:template.getApp());
            }
            // 获取商家的通知设置
            NotifyTemplateShop templateShop = notifyTemplateShopService.getOne(new LambdaQueryWrapper<NotifyTemplateShop>()
                    .eq(NotifyTemplateShop::getShopId, SecurityUtils.getShopUser().getShopId()).eq(NotifyTemplateShop::getTemplateId, template.getTemplateId()));
            if(Objects.nonNull(templateShop)) {
                // 设置商家的消息通知类型
                List<String> shopList = Arrays.asList(templateShop.getNotifyTypes().split(StrUtil.COMMA));
                for (String shopNotify : shopList) {
                    template.setShopSms(StrUtil.equals(shopNotify, "1") ? true : template.getShopSms());
                    template.setShopApp(StrUtil.equals(shopNotify, "3") ? true : template.getShopApp());
                    template.setShopSub(StrUtil.equals(shopNotify, "2") ? true : template.getShopSub());
                }
            }
            template.setTemplateTypeList(templateList);
        }
        return ResponseEntity.ok(templates);
    }

    private List<Integer> getTemplateList(String templateTypes) {
        String[] templateTypeList = templateTypes.split(StrUtil.COMMA);
        List<Integer> templates = new ArrayList<>();
        List<String> asList = Arrays.asList(templateTypeList);
        for (String templateStr : asList) {
            templates.add(Integer.valueOf(templateStr));
        }
        return templates;
    }


//    /**
//     * 使用说明模板批量替换
//     * @param ticketDto
//     */
//    private void replaceContent(MyCouponDto ticketDto,String nickName) {
//        Map<String,String> maps = new HashMap<>(24);
//        CouponDetail couponDetail = ticketDto.getCouponDetail();
//        String instruction = ticketDto.getInstruction();
//        if (StrUtil.isEmpty(instruction)) {
//            return;
//        }
//        String dates = DateUtil.format(ticketDto.getUserEndTime(), "yyyy-MM-dd");
//        //如果不是用户已经领取的优惠券，还需拼接下截止时间
//        if(ticketDto.getValidTimeType() != null && ticketDto.getValidTimeType() == 2){
//            dates = "自用户领取"+ticketDto.getAfterReceiveDays()+"天起生效到"+ticketDto.getValidDays()+"天后失效";
//        }
//        maps.put("deadline",dates);
//        maps.put("activityName",ticketDto.getCouponName());
//        maps.put("userName", nickName);
//        maps.put("sysName", "权益商城");
//        if(Objects.equals(ticketDto.getFinalCategory(),CouponType.OWN_CDKEY.value())){
//            List<Supplier> suppliers = couponShopService.getSupplierNameByCouponId(ticketDto.getCouponId());
//            StringBuilder names = new StringBuilder();
//            for (Supplier supplier : suppliers) {
//                names.append(supplier.getSupplierName()).append(StrUtil.COMMA);
//            }
//            if(StrUtil.isNotBlank(names)){
//                names.deleteCharAt(names.length() - 1);
//            }
//            maps.put("supplierName", names.toString());
//        }
//        if (Objects.equals(ticketDto.getFinalCategory(), CouponType.THEY_CDKEY.value())) {
//            maps.put("supplierName", "第三方供应商");
//        }
//        if(couponDetail != null){
//            if (ticketDto.getCouponDetail().getCashCondition() != null) {
//                maps.put("cashCondition", String.valueOf(couponDetail.getCashCondition()));
//            }
//            if (couponDetail.getQuotaDurationType() != null) {
//                maps.put("effectiveTime", couponDetail.getQuotaDurationType() == 0 ? "永久有效" : String.valueOf(couponDetail.getQuotaDurationType()));
//            }
//            if (couponDetail.getInstallmentType() != null) {
//                String type = couponDetail.getInstallmentType() == 1 ? "单笔分期类型" :
//                        couponDetail.getInstallmentType() == 2 ? "账单分期类型" : "全部分期类型";
//                maps.put("installmentType", type);
//            }
//            maps.put("installmentMinAmount", String.valueOf(couponDetail.getInstallmentMinAmount()));
//            maps.put("installmentReturnAmount", String.valueOf(couponDetail.getInstallmentReturnAmount()));
//            maps.put("amount", String.valueOf(couponDetail.getAmount()));
//            maps.put("duration", String.valueOf(couponDetail.getDuration()));
//        }
//        for(String key : maps.keySet()){
//            instruction = instruction.replace("${" + key + "}", maps.get(key));
//        }
//        ticketDto.setInstruction(instruction);
//    }
}
